package com.example.demo.common.utills;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.example.demo.mapper.UserMapper;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.management.DynamicMBean;
import javax.servlet.http.HttpSession;

@Slf4j
public class AliyunSmsUtils {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {
        String accessKeyId = PropertiesUtil.getValue("aliyun.accessKeyId");
        String accessKeySecret = PropertiesUtil.getValue("aliyun.accessKeySecret");
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    /**
     * 发送短信
     *
     * @param phoneNumbers 手机号，多个用,隔开
     * @throws Exception
     */
    public  static String SendSms(String phoneNumbers,UserMapper userMapper) throws Exception {
        String signName = PropertiesUtil.getValue("aliyun.signName");
        String templateCode = PropertiesUtil.getValue("aliyun.templateCode");
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phoneNumbers);
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        String code = RandomUtil.random();
        userMapper.insertCode(code);
        sendSmsRequest.setTemplateParam("{\"code\":"+code+"}");
        SendSmsResponse result = client.sendSms(sendSmsRequest);
        if (!result.body.code.equals("OK")) {
            return "fail";
        }
        return "success";
    }
}
